package util

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type JsonResponse struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

var statusMap = map[int]string{
	0:  "执行成功",
	-1: "执行失败",
	-2: "找不到对象",
	-3: "情况2",
}

var (
	StatusOk           = 0
	StatusErr          = -1
	StatusFindNotFound = -2
)

func Json(ctx *gin.Context, obj interface{}, err error) {
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, &JsonResponse{
			Code:    StatusErr,
			Message: err.Error(),
			Data:    nil,
		})
	} else {
		ctx.JSON(http.StatusOK, &JsonResponse{
			Code:    StatusOk,
			Message: "",
			Data:    obj,
		})
	}
}

func JsonWithCode(ctx *gin.Context, obj interface{}, code int, err error) {
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, &JsonResponse{
			Code:    code,
			Message: err.Error(),
			Data:    nil,
		})
	} else {
		ctx.JSON(http.StatusOK, &JsonResponse{
			Code:    code,
			Message: statusMap[code],
			Data:    obj,
		})
	}
}
